package io.seata.samples.tcc.springboot.springcloud.service;

import io.seata.samples.tcc.springboot.springcloud.action.TccActionOne;
import io.seata.samples.tcc.springboot.springcloud.action.TccActionTwo;
import io.seata.samples.tcc.springboot.springcloud.feign.ActionDbFeign;
import io.seata.samples.tcc.springboot.springcloud.feign.bean.User;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * The type Tcc transaction service.
 *
 * @author louis
 */
@Service
public class TccTransactionService {

    @Resource
    private TccActionOne tccActionOne;
    @Resource
    private TccActionTwo tccActionTwo;
    @Resource
    private ActionDbFeign actionDbFeign;

    /**
     * 测试分布式事务提交示例
     *
     * @return string string
     */
    @GlobalTransactional
    public String testCommit() {
        // 第一个TCC 事务参与者
        String result = tccActionOne.prepare("action-one-commit").getMessage();
        // 第二个TCC 事务参与者
        result = result + "\n" + tccActionTwo.prepare("action-two-commit").getMessage();
        // 数据库操作
        actionDbFeign.save(getUser());
        return result;
    }

    /**
     * 测试分布式事务回滚示例
     * @return string string
     */
    @GlobalTransactional
    public String testRollback() {
        //第一个TCC 事务参与者
        String result = tccActionOne.prepare("action-one-rollback").getMessage();
        // 第二个TCC 事务参与者
        result = result + "\n" + tccActionTwo.prepare("action-two-rollback").getMessage();
        // 数据库操作
        actionDbFeign.save(getUser());
        throw new RuntimeException(result);
    }

    private User getUser() {
        User user = new User();
        user.setId(3L);
        user.setUsername("张三");
        return user;
    }
}
